<?php
// 前台取消默认加载的 jquery   
if ( !is_admin() ) { // 后台不用
      wp_deregister_script( 'jquery' );
}
// 移除3.0以上默认的 Admin_bar 
add_filter( 'show_admin_bar', '__return_false' ); 
// 移除版本号
remove_action('wp_head', 'wp_generator');
// 移除3.0以上默认的 l10n.js
wp_deregister_script('l10n' );
/* 删除文章发布页面不需要的模块 */
add_action('admin_init','customize_meta_boxes');
function customize_meta_boxes() {
     // 删除以下两个模块postexcerpt 、postexcerpt
     remove_meta_box('postexcerpt','post','normal'); //摘要
     remove_meta_box('trackbacksdiv','post','normal'); //发送trackbacks
     remove_meta_box('postcustom','post','normal'); //自定义域
    // remove_meta_box('commentstatusdiv','post','normal'); //讨论
     remove_meta_box('authordiv','post','normal'); //作者
    // remove_meta_box('commentsdiv','post','normal'); // 评论
     remove_meta_box('slugdiv','post','normal'); //文章别名
     remove_meta_box('revisionsdiv','post','normal'); //文章修订版
}
/*移除管理菜单*/
function wps_admin_bar() {
    global $wp_admin_bar;
    $wp_admin_bar->remove_menu('wp-logo');
    $wp_admin_bar->remove_menu('about');
    $wp_admin_bar->remove_menu('wporg');
    $wp_admin_bar->remove_menu('documentation');
    $wp_admin_bar->remove_menu('support-forums');
    $wp_admin_bar->remove_menu('feedback');
    $wp_admin_bar->remove_menu('view-site');
}
add_action( 'wp_before_admin_bar_render', 'wps_admin_bar' );
/* HTTP Gzip */
function wp_gzip() {
  // Dont use on Admin HTML editor
  if ( strstr($_SERVER['REQUEST_URI'], '/js/tinymce') )
    return false;
  // Can't use zlib.output_compression and ob_gzhandler at the same time
  if ( ( ini_get('zlib.output_compression') == 'On' || ini_get('zlib.output_compression_level') > 0 ) || ini_get('output_handler') == 'ob_gzhandler' )
    return false;
  // Load HTTP Compression if correct extension is loaded
  if (extension_loaded('zlib') && !ob_start('ob_gzhandler'))
    ob_start();
}
add_action('init', 'wp_gzip');
/* UTF-8 substr() for none mb_substr() */
if ( !function_exists('mb_substr') ) {
  function mb_substr( $str, $start, $length, $encoding ) {
    return preg_replace( '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $start . '}'.
    '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $length . '}).*#s', '$1', $str);
  }
}
// 自定义菜单
register_nav_menus( array( 'header-menu' =>'头部导航'));
// 自定义侧边栏
if ( function_exists('register_sidebar') )
 register_sidebar(array(
		'name'			=> 'all sidebar Widget'
		//'before_widget' => '<li>',
		//'after_widget' => '</ul></li>',
		//'before_title' => '<h2>',
		//'after_title' => '</h2><ul>'
    ));
/* 在后台添加菜单中将“首页”加入 选项中 */
function home_page_menu_args( $args ) {
    $args['show_home'] = true;
    return $args;
}
add_filter( 'wp_page_menu_args', 'home_page_menu_args' );
/* Add post formats */
//add_theme_support('post-formats', array( 'aside', 'gallery','chat','link','image','quote','status','video') );
/* 文章目录功能 */
function article_index($content) {
	if(!is_singular()){ // 不是文章页面，不添加
		return $content;
	}
    $matches = array();
    $ul_li = '';
    $r = "/<h2>([^<]+)<\/h2>/im";
    if(preg_match_all($r, $content, $matches)) {
        foreach($matches[1] as $num => $title) {
            $content = str_replace($matches[0][$num], '<h2 id="title-'.$num.'">'.$title.'</h2>', $content);
            $ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
        }
        $content = "\n<div id=\"article-index\">
                <strong>文章目录</strong>
                <ul id=\"index-ul\">\n" . $ul_li . "</ul>
            </div>\n" . $content;
    }
    return $content;
}
add_filter( "the_content", "article_index" );
/* 自定义分页 暂时不用
function king51_nav( $p = 2 ) { // 取当前页前后各 2 页
		if ( is_singular() ) return; // 文章与插页不用
		global $wp_query, $paged;
		$max_page = $wp_query->max_num_pages;
		if ( $max_page == 1 ) return; // 只有一页不用
		if ( empty( $paged ) ) $paged = 1;
		//echo '<span class="pages">Page: ' . $paged . ' of ' . $max_page . ' </span> '; // 显示页数
		if ( $paged > 1 ) p_link( $paged - 1, '上一页', '« Previous' );// 如果当前页大于1就显示上一页链接 
		if ( $paged > $p + 1 ) p_link( 1, '最前页' );
		if ( $paged > $p + 2 ) echo '... ';
		for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { // 中间页
			if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span> " : p_link( $i );
		}
		if ( $paged < $max_page - $p - 1 ) echo '... ';
		if ( $paged < $max_page - $p ) p_link( $max_page, '最后页' );
		if ( $paged < $max_page ) p_link( $paged + 1,'下一页', 'Next »' );// 如果当前页不是最后一页显示下一页链接 
	}
	function p_link( $i, $title = '', $linktype = '' ) {
		if ( $title == '' ) $title = "第 {$i} 页";
		if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
		echo "<a class='page-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$linktext}</a> ";
}

	// -- END ----------------------------------------*/
	
/* 自定义分页类型2 取自千鸟志 */
function king51_nav2( $p = 2 ) { // 取当前页前后各 2 页
	if ( is_singular() ) return; // 文章与插页不用
	global $wp_query, $paged;
	$max_page = $wp_query->max_num_pages;
	if ( $max_page == 1 ) return; // 只有一页不用
	if ( empty( $paged ) ) $paged = 1;
	if ( $paged > 1 ) p_link( 1, '最前页' );
	if ( $paged > 2 ) echo '... ';
	if ( $paged > 1 ) p_link( $paged - 1, '上一页', '< ' );/* 如果当前页大于1就显示上一页链接 */
	print "<span class='page-numbers current'>{$paged}</span> ";
//	for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { // 中间页
//	if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span> " : p_link( $i );
//	}
	if ( $paged < $max_page - 1 ) p_link( $paged + 1,$paged + 1,'Older Entries>');/* 如果当前页不是最后一页显示下一页链接 */
	if ( $paged < $max_page - 1 ) echo '... ';
	if ( $paged < $max_page ) p_link( $max_page, '最后页' );
}
function p_link( $i, $title = '', $linktype = '' ) {
	if ( $title == '' ) $title = "第 {$i} 页";
	if ( $linktype == '' ) { $linktext = $i; } else { $linktext = $linktype; }
	echo "<a class='page-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$linktext}</a> ";
}
	// -- END ----------------------------------------
	
	
/* <<小墙>> Anti-Spam v1.82 by Willin Kan. 2010/12/16 最新修改  */
//建立
/* 与多说评论插件冲突，暂时禁用
class anti_spam {
  function anti_spam() {
    if ( !current_user_can('level_0') ) {
      add_action('template_redirect', array($this, 'w_tb'), 1);
      add_action('init', array($this, 'gate'), 1);
      add_action('preprocess_comment', array($this, 'sink'), 1);
    }}
  //设栏位
  function w_tb() {
    if ( is_singular() ) {
      ob_start(create_function('$input','return preg_replace("#textarea(.*?)name=([\"\'])comment([\"\'])(.+)/textarea>#",
      "textarea$1name=$2w$3$4/textarea><textarea name=\"comment\" cols=\"100%\" rows=\"4\" style=\"display:none\"></textarea>",$input);') );
    }}
  //检查
  function gate() {
    if ( !empty($_POST['w']) && empty($_POST['comment']) ) {
      $_POST['comment'] = $_POST['w'];
    } else {
      $request = $_SERVER['REQUEST_URI'];
      $referer = isset($_SERVER['HTTP_REFERER'])         ? $_SERVER['HTTP_REFERER']         : '隐瞒';
      $IP      = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] . ' (透过代理)' : $_SERVER["REMOTE_ADDR"];
      $way     = isset($_POST['w'])                      ? '手动操作'                       : '未经评论表格';
      $spamcom = isset($_POST['comment'])                ? $_POST['comment']                : null;
      $_POST['spam_confirmed'] = "请求: ". $request. "\n来路: ". $referer. "\nIP: ". $IP. "\n方式: ". $way. "\n内容: ". $spamcom. "\n -- 记录成功 --";
    }}
  //处理
  function sink( $comment ) {
    if ( !empty($_POST['spam_confirmed']) ) {
      if ( in_array( $comment['comment_type'], array('pingback', 'trackback') ) ) return $comment; //不管 Trackbacks/Pingbacks
      //方法一: 直接挡掉, 将 die(); 前面两斜线删除即可.
      die();
      //方法二: 标记为 spam, 留在资料库检查是否误判.
      //add_filter('pre_comment_approved', create_function('', 'return "spam";'));
     // $comment['comment_content'] = "[ 小墙判断这是Spam! ]\n". $_POST['spam_confirmed'];
    }
    return $comment;
  }}
$anti_spam = new anti_spam();
*/
// -- END ----------------------------------------
/* Auto-description v1.3 by Willin Kan. */
function head_meta_desc() {
  global $s, $post;
  $description = '';
  $blog_name = get_bloginfo('name');
  if ( is_singular() ) {
    if( !empty( $post->post_excerpt ) ) {
      $text = $post->post_excerpt;
    } else {
      $text = $post->post_content;
    }
    $description = trim( str_replace( array( "\r\n", "\r", "\n", "　", " "), " ", str_replace( "\"", "'", strip_tags( $text ) ) ) );
    if ( !( $description ) ) $description = $blog_name . " - " . trim( wp_title('', false) );
  } elseif ( is_home () )    { $description = $blog_name . " - " . get_bloginfo('description') . " 一个程序员出身的IT Manager，主要记录技术和生活，涉及企业管理，财务管理，hr等。"; // 首页要自己加
  } elseif ( is_tag() )      { $description = $blog_name . "有关 '" . single_tag_title('', false) . "' 的文章";
  } elseif ( is_category() ) { $description = $blog_name . "有关 '" . single_cat_title('', false) . "' 的文章";
  } elseif ( is_archive() )  { $description = $blog_name . "在: '" . trim( wp_title('', false) ) . "' 的文章";
  } elseif ( is_search() )   { $description = $blog_name . ": '" . esc_html( $s, 1 ) . "' 的搜索结果";
  } else { $description = $blog_name . "有关 '" . trim( wp_title('', false) ) . "' 的文章";
  }
  $description = mb_substr( $description, 0, 97, 'utf-8' ) . '..';
  echo "<meta name=\"description\" content=\"$description\" />\n";
}
add_action('wp_head', 'head_meta_desc');
/* 面包屑导航 */
function dimox_breadcrumbs() {
  $delimiter = '&raquo;';
  $name = '首页'; //text for the 'Home' link
  $currentBefore = '<span>';
  $currentAfter = '</span>';
  if ( !is_home() && !is_front_page() || is_paged() ) {
    echo '<h6>';
    global $post;
    $home = get_bloginfo('url');
    echo '<a href="' . $home . '">'.$name.'</a>'.$delimiter.' ';
    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $currentBefore . 'Archive by category &#39;';
      single_cat_title();
      echo '&#39;' . $currentAfter;
    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('d') . $currentAfter;
    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('F') . $currentAfter;
    } elseif ( is_year() ) {
      echo $currentBefore . get_the_time('Y') . $currentAfter;
    } elseif ( is_single() ) {
      $cat = get_the_category(); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && !$post->post_parent ) {
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_search() ) {
      echo $currentBefore . 'Search results for &#39;' . get_search_query() . '&#39;' . $currentAfter;
    } elseif ( is_tag() ) {
      echo $currentBefore . 'Posts tagged &#39;';
      single_tag_title();
      echo '&#39;' . $currentAfter;
    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $currentBefore . 'Articles posted by ' . $userdata->display_name . $currentAfter;
    } elseif ( is_404() ) {
      echo $currentBefore . 'Error 404' . $currentAfter;
    }
    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }
    echo '</h6>';
  }
}
/* 嵌套评论代码 */
function king51_comment( $comment, $args, $depth ) {
 $GLOBALS['comment'] = $comment; ?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<div id="comment-<?php comment_ID(); ?>">
		<div class="comment-author vcard">
			<?php echo get_avatar( $comment, 50 ); ?>
			
		<!-- .comment-author .vcard -->
	<header><?php echo get_comment_author_link(); ?>	
			<time datetime="<?php echo get_comment_date() . '' . get_comment_time(); ?>">
				<?php comment_date() ; ?>
			</time>
			<?php edit_comment_link(  '(Edit)', ' ' );?>
	</header><!-- .comment-meta .commentmetadata -->
			</div
		<dd class="comment-body">
			<?php if ( $comment->comment_approved == '0' ) : ?>
			<em> 您的评论等待审核。</em>
			<?php endif; ?>
			<?php comment_text(); ?>
		
		<div class="reply">
			<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
		</div></dd><!-- .reply -->
	</div><!-- #comment-##  -->
	<?php
}
/* Mini Gavatar Cache by King51. */
//function my_avatar($avatar) {
//  $tmp = strpos($avatar, 'http');
//  $g = substr($avatar, $tmp, strpos($avatar, "'", $tmp) - $tmp);
//  $tmp = strpos($g, 'avatar/') + 7;
//  $f = substr($g, $tmp, strpos($g, "?", $tmp) - $tmp);
//  $w = get_bloginfo('template_directory');
//  $e = get_template_directory() .'/avatar/'. $f .'.jpg';
//  $t = 1209600; //設定14天, 單位:秒
//  if ( !is_file($e) || (time() - filemtime($e)) > $t ) { //当头像不存在或者超过14天更新一下
//    copy($g, $e);
//  } else  $avatar = strtr($avatar, array($g => $w.'/avatar/'.$f.'.jpg'));
//  if (filesize($e) < 500) copy( $w.'/avatar/default.jpg', $e);
//  return $avatar;
//}
//add_filter('get_avatar', 'my_avatar');
// -- END ----------------------------------------
/*  侧边栏的缓存更新机制 */
//评论
function clear_rc_comments() {
  update_option('rc_comments', ''); // 清空 rc_comments
}
add_action('comment_post', 'clear_rc_comments'); // 新评论
add_action('edit_comment', 'clear_rc_comments'); // 编辑评论
add_action('trashed_comment', 'clear_rc_comments'); // 当评论转移到回收站
//标签
function clear_rc_tags() {
  update_option('rc_tags', ''); // 清空 rc_comments
}	
add_action('save_post', 'clear_rc_tags'); // 关于Post的任何操作
	 
/* 动态修改 WordPress Heading 标签 */
function wp_dynamic_headings( $content ) {
	if(is_singular()){
		return $content;
	}
	$content = str_replace( array( '<h5', '</h5>' ), array( '<h6', '</h6>' ), $content );
	$content = str_replace( array( '<h4', '</h4>' ), array( '<h5', '</h5>' ), $content );
	$content = str_replace( array( '<h3', '</h3>' ), array( '<h4', '</h4>' ), $content );
	$content = str_replace( array( '<h2', '</h2>' ), array( '<h3', '</h3>' ), $content );
	return $content;
}
add_filter( 'the_content', 'wp_dynamic_headings' );
// 把标签输出变成彩色
function colorCloud($text) {
$text = preg_replace_callback('|<a (.+?)>|i', 'colorCloudCallback', $text);
return $text;
}
function colorCloudCallback($matches) {
$text = $matches[1];
$color = dechex(rand(0,16777215));
$pattern = '/style=(\'|\")(.*)(\'|\")/i';
$text = preg_replace($pattern, "style=\"color:#{$color};$2;\"", $text);
return "<a $text>";
} 
?>